package com.aos.util;

import com.aos.properties.APMSProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName ValidateUtils
 * @Description:验证码工具
 * @Author wumingwang
 * @Date 2018/9/18 14:16
 * @Version 1.0
 */
@Component
@Slf4j
public class ValidateUtils {

    public static final int width = 100;
    public static final int height = 30;
    public static final int codeCount = 4;
    public static final int lineCount = 10;

    @Autowired
    private APMSProperties aPMSProperties;

    @Autowired
    private RedisUtils redisUtils;

    public Result createCaptchaSaveInCache() {
        log.info("生成图片验证码");
        ByteArrayOutputStream out = null;
        try {
            ValidateCode vCode = new ValidateCode(width, height, codeCount, lineCount);
            String captcha = vCode.getCode();
            out = new ByteArrayOutputStream();
            ImageIO.write(vCode.getBuffImg(), "jpg", out);
            byte[] b = out.toByteArray();
            String base64Img = "data:image/jpg;base64,"+Base64Utils.encode(b);
            //保存在缓存中
            String captchaKey = aPMSProperties.getCommon().getVerificationCodeKey()+"_"+MD5Utils.getSalt();
            redisUtils.setString(captchaKey, captcha,30*60L,TimeUnit.SECONDS);
            log.info("生成图片验证码成功：captchaKey={}, captcha={}", captchaKey, captcha);

            Map<String, Object> map = new HashMap<>();
            map.put("base64Img", base64Img);
            map.put("captchaKey", captchaKey);
            return Result.ok(map);
        } catch (Exception e) {
            log.error("图片验证码生成失败", e);
            return Result.error("图片验证码生成失败");
        }finally{
            try {
                if(out != null){
                    out.close();
                }
            } catch (IOException e) {
                log.error("流关闭异常", e);
            }
        }
    }
}
